/*
 * Project: Twitter Bootstrap Hover Dropdown
 * Author: Cameron Spear
 * Contributors: Mattia Larentis
 *
 * Dependencies?: Twitter Bootstrap's Dropdown plugin
 *
 * A simple plugin to enable twitter bootstrap dropdowns to active on hover and provide a nice user experience.
 *
 * No license, do what you want. I'd love credit or a shoutout, though.
 *
 * http://cameronspear.com/blog/twitter-bootstrap-dropdown-on-hover-plugin/
 */
;(function($, win, undefined) {
    // outside the scope of the jQuery plugin to
    // keep track of all dropdowns
    var $allDropdowns = $();

    // if instantlyCloseOthers is true, then it will instantly
    // shut other nav items when a new one is hovered over
    $.fn.dropdownHover = function(options) {

        // the element we really care about
        // is the dropdown-toggle's parent
        $allDropdowns = $allDropdowns.add(this.parent());

        return this.each(function() {
            var $this = $(this).parent(),
                defaults = {
                    delay: 100,
                    instantlyCloseOthers: true
                },
                data = {
                    delay: $(this).data('delay'),
                    instantlyCloseOthers: $(this).data('close-others')
                },
                settings = $.extend(true, {}, defaults, options, data),
                timeout;

            $this.hover(function() {
                if(settings.instantlyCloseOthers === true)
                    $allDropdowns.removeClass('open');

                win.clearTimeout(timeout);
                $(this).addClass('open');
            }, function() {
                timeout = win.setTimeout(function() {
                    $this.removeClass('open');
                }, settings.delay);
            });
        });
    };

    // apply dropdownHover to all elements with the data-hover="dropdown" attribute
    $(document).ready(function() {
        $('[data-hover="dropdown"]').dropdownHover();
    });
})(jQuery, window);

$.app = {
    /**
     * 当前显示的窗口队列
     */
    _layerQueue: null,
    _pushLayer: function(index) {
        if(!$.app._layerQueue) {
            $.app._layerQueue = [];
        }
        $.app._layerQueue.push(index);
    },
    _popLayer: function() {
        if ($.app._layerQueue && $.app._layerQueue.length > 0) {
            return $.app._layerQueue.pop();
        }
        return null;
    },
    _closeLayer: function() {
        if($.app._layerQueue && $.app._layerQueue.length > 0) {
            $.app.close($.app._layerQueue.pop());
        }
    },
    close: function(index) {
        if (index) {
            layer.close(index);
        } else {
            layer.closeAll();
        }
    },

    /**
     * 打开加载loading
     */
    openLoading: function(msg) {
        var index = layer.msg(msg || '正在处理，请稍后...', {icon: 16 ,shade: 0.3, end: $.app._popLayer});
        $.app._pushLayer(index);
        return index;
    },
    /**
     * 关闭加载loading
     */
    closeLoading: function() {
        $.app._closeLayer();
    },

    /**
     * 打开对话框
     */
    openDialog : function(title, url, settings) {
        var that = this;

        $.app.openLoading();
        var defaultSettings = {
            type: 1,
            title : title,
            scrollbar: false,
            area: ['500px', '350px'],
            skin: 'layui-layer-rim',
            end: $.app._popLayer(),
            yes: function(index, $layer) {
                var close = true;
                if ($.isFunction(settings.confirm)) {
                    close = settings.confirm(index, $layer);
                }
                close && that.close(index);
            },
            btn1: function (index, $layer) {
                var close = true;
                if ($.isFunction(settings.cancel)) {
                    settings.cancel(index, $layer);
                }
                close && that.close(index);
            }
        };

        settings = $.extend(true, {}, defaultSettings, settings);
        if (!settings.btn) {
            settings.btn = false;
        }

        var index = -1;
        $.ajax({
            url: url,
            headers: { table: true }
        }).done(function (data) {
            $.app.closeLoading();
            settings.content = data;
            index = layer.open(settings);
            $.app._pushLayer(index);
        });

        return index;
    },
    /**
     * 关闭对话框
     */
    closeDialog : function() {
        $.app._closeLayer();
    },

    /**
     * 提示框
     */
    alert : function(msg, callback, options) {

        if ($.isPlainObject(callback)) {
            options = callback;
            callback = null;
        }

        var settings = $.extend({}, {
            title : "提醒",
            shade: 0.6,
            btn: ['关闭']
        }, options);

        settings.end = function(){
            //$.app._popLayer();
            callback && callback();
        };

        var index = layer.alert(msg, settings);
        //$.app._pushLayer(index);
        return index;
    },
    /**
     * 确认框
     */
    confirm : function(msg, confirm, cancel, options) {
        var that = this;

        options = options || {};
        if ($.isPlainObject(cancel)) {
            options = cancel;
            cancel = null;
        }

        var layerEnd = options.end;
        options.end = function() {
            //$.app._popLayer();
            layerEnd && layerEnd();
        };

        var index = layer.confirm(msg,  options, function(index) {
            var close = true;
            if ($.isFunction(confirm)) {
                close = confirm(index);
            }
            close && that.close(index);
        }, function(index) {
            var close = true;
            if ($.isFunction(cancel)) {
                close = cancel(index);
            }
            close && that.close(index);
        });

        //$.app._pushLayer(index);
        return index;
    },
    isImage : function(filename) {
        return /gif|jpe?g|png|bmp$/i.test(filename);
    },
    removeContextPath : function(url) {
        if(url.indexOf(ctx) === 0) {
            return url.substr(ctx.length);
        }
        return url;
    },
    /**
     * 将$("N").val() ----> [1,2,3]
     */
    joinVar : function(elem, separator) {
        if(!separator) {
            separator = ",";
        }
        var array = [];
        $(elem).each(function() {
            array.push($(this).val());
        });

        return array.join(separator);
    }
};

$.table = {
    /**
     * 初始化表格：全选/反选 排序
     */
    initTable: function (table) {
        if(!table || !table.length || table.attr("initialized") === "true") {
            return;
        }

        table.attr("initialized", "true");

        $.table.initSort(table);
        $.table.initSearchForm(table);
        if(table.is(".move-table")) {
            $.movable.initMoveableTable(table);
        }

        //初始化table里的a标签
        $.table.initTableBtn(table);
        //初始化删除和修改按钮
        $.table.initDeleteSelected(table);
        $.table.initUpdateSelected(table);
        $.table.initCreate(table);

        //初始化checkbox
        $.table.initCheckbox(table);
        //初始化 按钮的状态
        $.table.changeBtnState(table);
    },
    initCheckbox: function(table) {
        var activeClass = "active";
        //初始化表格中checkbox 点击单元格选中
        table.find("td.check").each(function () {
            var checkbox = $(this).find(":checkbox,:radio");
            checkbox.off("click").on("click", function (event) {
                var checked = checkbox.is(":checked");
                if(!checked) {
                    checkbox.closest("tr").removeClass(activeClass);
                } else {
                    checkbox.closest("tr").addClass(activeClass);
                }
                $.table.changeBtnState(table);
                event.stopPropagation();
            });
            $(this).closest("tr").off("click").on("click", function () {
                var checked = checkbox.is(":checked");
                if(checked) {
                    checkbox.closest("tr").removeClass(activeClass);
                } else {
                    checkbox.closest("tr").addClass(activeClass);
                }
                checkbox.prop("checked", !checked);
                $.table.changeBtnState(table);
            });
        });
        //初始化全选反选
        table.find(".check-all").off("click").on("click", function () {
            var checkAll = $(this);
            if(checkAll.text() === '全选') {
                checkAll.text("取消");
                table.find("td.check :checkbox").prop("checked", true).closest("tr").addClass(activeClass);
            } else {
                checkAll.text("全选");
                table.find("td.check :checkbox").prop("checked", false).closest("tr").removeClass(activeClass);
            }
            $.table.changeBtnState(table);
        });
        table.find(".reverse-all").off("click").on("click", function () {
            table.find("td.check :checkbox").each(function () {
                var checkbox = $(this);
                var checked = checkbox.is(":checked");
                if(checked) {
                    checkbox.closest("tr").removeClass(activeClass);
                } else {
                    checkbox.closest("tr").addClass(activeClass);
                }
                checkbox.prop("checked", !checked);
                $.table.changeBtnState(table);
            });
        });
    },
    changeBtnState : function(table) {
        var hasChecked = table.find("td.check :checkbox:checked").length;
        var btns = table.closest(".panel").find(".tool .btn").not(".no-disabled");
        if(hasChecked) {
            btns.removeClass("disabled");
            btns.each(function() {
                var btn = $(this);
                var href = btn.data("btn-state-href");
                if(href) {
                    btn.attr("href", href);
                }
            });
        } else {
            btns.addClass("disabled");
            btns.each(function() {
                var btn = $(this);
                var href = btn.attr("href");
                if(href) {
                    btn.data("btn-state-href", href);
                    btn.removeAttr("href");
                }
            });
        }
    },
    /**
     * 初始化对应的查询表单
     */
    initSearchForm : function(table) {
        var id = $(table).attr("id");
        var searchForm = table.closest("[data-table='" + id + "']").find(".search-form");

        if(!searchForm.length) {
            return;
        }

        searchForm.find(".btn").addClass("no-disabled");

        searchForm.find(".btn-clear-search").click(function() {

            if (table.data("async") === true) {
                var resetBtn = searchForm.find("input[type='reset']");
                if(!resetBtn.length) {
                    searchForm.append("<input type='reset' style='display:none'>");
                    resetBtn = searchForm.find("input[type='reset']");
                }
                resetBtn.click();
            }
            turnSearch(table, searchForm, true);
        });

        var turnSearch = function(table, searchForm, isSearchAll) {
            var url = $.table.tableURL(table);
            url = $.table.removeSearchParam(url, searchForm);
            url = $.table.removePageParam(url, searchForm);
            if(!isSearchAll) {
                if(url.indexOf("?") === -1) {
                    url = url + "?";
                } else {
                    url = url + "&";
                }
                url = url + searchForm.serialize();
            }
            $.table.reloadTable(table, url, null);
        };

        searchForm.off("submit").on("submit", function() {
            turnSearch(table, searchForm, false);
            return false;
        });

        if(searchForm.is("[data-change-search=true]")) {
            searchForm.find(":input:not(:button,:submit,:reset)").off("change").on("change", function(e) {
                // avoid double search issue, when you click search button after change any input
                searchForm.off("submit").on("submit", function() {
                    return false;
                });
                turnSearch(table, searchForm, false);
            });
        }

        searchForm.find(".btn-search-all").off("click").on("click", function() {
            turnSearch(table, searchForm, true);
            return false;
        });


    },
    /**
     * 初始化sort
     */
    initSort: function (table) {
        if (!table.length) {
            return;
        }

        //初始化排序
        var prefix = $.table.getPrefix(table);

        var sortURL = $.table.tableURL(table);

        var sortBtnTemplate = '<div class="sort"><a class="{sort-icon}" href="#" title="排序"></a></div>';
        table.find("[sort]").each(function () {
            var th = $(this);
            var sortPropertyName = prefix + "sort." + th.attr("sort");
            var sortBtnStr = null;
            var matchResult = sortURL.match(new RegExp(sortPropertyName + "=(asc|desc)", "gi"));
            var order = null;
            if (matchResult) {
                order = RegExp.$1;
                if (order === 'asc') {
                    sortBtnStr = sortBtnTemplate.replace("{sort-icon}", "sort-hover icon-arrow-up");
                } else if (order === 'desc') {
                    sortBtnStr = sortBtnTemplate.replace("{sort-icon}", "sort-hover icon-arrow-down");
                }
            }
            if (sortBtnStr == null) {
                sortBtnStr = sortBtnTemplate.replace("{sort-icon}", "icon-arrow-down");
            }
            th.wrapInner("<div class='sort-title'></div>").append($(sortBtnStr));

            //当前排序
            th.prop("order", order);//设置当前的排序 方便可移动表格

            th.addClass("sort-th").click(function () {
                sortURL = $.table.tableURL(table);
                //清空上次排序
                sortURL = $.table.removeSortParam(sortURL);

                if (!order) { //asc
                    order = "asc";
                } else if (order === "asc") { //desc
                    order = "desc";
                } else if (order === "desc") { //none
                    order = "asc";
                }

                if (order) {
                    sortURL = sortURL + (sortURL.indexOf("?") === -1 ? "?" : "&");
                    sortURL = sortURL + sortPropertyName + "=" + order;
                }

                $.table.reloadTable(table, sortURL, null);
            });

        });
    },
    /**
     * 分页
     */
    turnPage: function (pageSize, pn, child) {
        var table = $(child).closest(".table-pagination").prev("table");
        if(!table.length) {
            table = $(child).closest("table");
        }

        var pageURL = $.table.tableURL(table);

        //清空上次分页
        pageURL = $.table.removePageParam(pageURL);


        pageURL = pageURL + (pageURL.indexOf("?") === -1 ? "?" : "&");

        var prefix = $.table.getPrefix(table);
        pageURL = pageURL + prefix + "page.num=" + pn;

        if (pageSize) {
            pageURL = pageURL + "&" + prefix + "page.size=" + pageSize;
        }

        $.table.reloadTable(table, pageURL, null);
    },
    /**
     * 执行跳转
     */
    reloadTable: function (table, url, backURL) {

        if(!url) {
            url = $.table.tableURL(table);
        }

        if (!backURL) {
            backURL = url;
        }
        //modalDialog时 把当前url保存下来方便翻页和排序
        table.closest(".ui-dialog").data("url", backURL);

        if (table.data("async") === true) {
            $.app.openLoading();

            var tableId = table.attr("id");
            var containerId = table.data("async-container");
            var headers = {};

            if(!containerId) {//只替换表格时使用
                headers.table = true;
            } else {
                headers.container = true;
            }

            $.ajax({
                url: url,
                async:true,
                headers: headers
            }).done(function (data) {
                if (containerId) {//装载到容器
                    $("#" + containerId).replaceWith(data);
                } else {
                    var pagination = table.next(".table-pagination");
                    if(pagination.length) {
                        pagination.remove();
                    }
                    table.replaceWith(data);
                }

                table = $("#" + tableId);
                table.data("url", backURL);
                $.table.initTable(table);

                var callback = table.data("async-callback");
                if(callback && window[callback]) {
                    window[callback](table);
                }

                $.app.closeLoading();
            });
        } else {
            window.location.href = url;
        }
    },
    /**
     * 获取表格对于的url
     */
    tableURL : function(table) {
        var $dialog = table.closest(".ui-dialog");

        var url = table.data("url");
        if(!url && $dialog.length) {
            //openDialog
            url = $dialog.data("url");
        }
        if (!url) {
            url = window.location.href;
        }
        //如果URL中包含锚点（#） 删除
        if(url.indexOf("#") > 0) {
            url = url.substring(0, url.indexOf("#"));
        }

        return url;
    },
    encodeTableURL : function(table) {
        return encodeURIComponent($.table.tableURL(table));
    },
    /**
     * 获取传递参数时的前缀
     */
    getPrefix : function(table) {
        var prefix = table.data("prefix");
        if (!prefix) {
            prefix = "";
        } else {
            prefix = prefix + "_";
        }
        return prefix;
    },
    removePageParam : function(pageURL) {
        pageURL = pageURL.replace(/&\w*page.num=\d+/gi, '');
        pageURL = pageURL.replace(/\?\w*page.num=\d+&/gi, '?');
        pageURL = pageURL.replace(/\?\w*page.num=\d+/gi, '');
        pageURL = pageURL.replace(/&\w*page.size=\d+/gi, '');
        pageURL = pageURL.replace(/\?\w*page.size=\d+&/gi, '?');
        pageURL = pageURL.replace(/\?\w*page.size=\d+/gi, '');
        return pageURL;
    },
    removeSortParam : function(sortURL) {
        sortURL = sortURL.replace(/&\w*sort.*=((asc)|(desc))/gi, '');
        sortURL = sortURL.replace(/\?\w*sort.*=((asc)|(desc))&/gi, '?');
        sortURL = sortURL.replace(/\?\w*sort.*=((asc)|(desc))/gi, '');
        return sortURL;
    },
    removeSearchParam : function(url, form) {
        $.each(form.serializeArray(), function() {
            var name = this.name;
            url = url.replace(new RegExp(name + "=.*?\&","g"), '');
            url = url.replace(new RegExp("[\&\?]" + name + "=.*$","g"), '');
        });
        return url;
    },
    /**
     * 格式化url前缀，默认清除url ? 后边的
     */
    formatUrlPrefix : function(urlPrefix, $table) {

        if(!urlPrefix) {
            urlPrefix = $table.data("prefix-url");
        }

        if(!urlPrefix && $table && $table.length) {
            urlPrefix = decodeURIComponent($.table.tableURL($table));
        }

        if(!urlPrefix) {
            urlPrefix = currentURL;
        }

        if(urlPrefix.indexOf("?") >= 0) {
            return urlPrefix.substr(0, urlPrefix.indexOf("?"));
        }
        return urlPrefix;
    },
    initDeleteSelected : function($table, urlPrefix) {
        if(!$table || !$table.length) {
            return;
        }

        var $btn = $table.closest("[data-table='" + $table.attr("id") + "']").find(".btnDelete:not(.btn-custom)");
        urlPrefix = $.table.formatUrlPrefix(urlPrefix, $table);
        $btn.off("click").on("click", function() {
            var checkbox = $.table.getAllSelectedCheckbox($table);
            if(!checkbox.length)  return;

            $.app.confirm('确定删除选择的数据吗？', function() {
                window.location.href =
                    urlPrefix + "/batch/delete?" + checkbox.serialize() + "&BackURL=" + $.table.encodeTableURL($table);
                return true;
            });
        });
    },
    initUpdateSelected : function($table, urlPrefix) {
        if(!$table || !$table.length) {
            return;
        }
        var $btn = $table.closest("[data-table='" + $table.attr("id") + "']").find(".btnUpdate:not(.btn-custom)");
        urlPrefix = $.table.formatUrlPrefix(urlPrefix, $table);
        $btn.off("click").on("click", function() {
            var checkbox = $.table.getFirstSelectedCheckbox($table);
            if(!checkbox.length)  return;
            var id = checkbox.val();
            $.app.openDialog('修改', urlPrefix + "/" + id + "/update?BackURL=" + $.table.encodeTableURL($table));
        });
    },
    initCreate : function($table, urlPrefix) {
        if(!$table || !$table.length) {
            return;
        }
        var $btn = $table.closest("[data-table='" + $table.attr("id") + "']").find(".btnCreate");

        $btn.addClass("no-disabled");

        $btn.off("click").on("click", function() {
            var url =  $.table.formatUrlPrefix(urlPrefix, $table) + "/create";
            if($btn.attr("href")) {
                url = $btn.attr("href");
            }
            $.app.openDialog('添加', url + (url.indexOf("?") === -1 ? "?" : "&") + "BackURL=" + $.table.encodeTableURL($table));
            return false;
        });
    },
    initTableBtn : function($table, urlPrefix) {
        if(!$table || !$table.length) {
            return;
        }
        $table.closest("[data-table=" + $table.attr("id") + "]").find(".btn").not(".btn-custom,.btnCreate,.btnUpdate,.btnDelete").each(function() {
            var $btn = $(this);
            var url = $btn.attr("href");
            if(!url || url.indexOf("#") === 0 || url.indexOf("javascript:") === 0) {//没有url就不处理了
                return;
            }
            $btn.off("click").on("click", function() {
                window.location.href = url + (url.indexOf("?") === -1 ? "?" : "&") + "BackURL=" + $.table.encodeTableURL($table);
                return false;
            });
        });

        urlPrefix = $.table.formatUrlPrefix(urlPrefix, $table);
        //支持双击编辑
        if($table.hasClass("table-dblclick-edit")) {
            $table.children("tbody").children("tr").off("dblclick").on("dblclick", function() {
                var id = $(this).find(":checkbox[name=ids]").val();
                window.location.href = urlPrefix + "/" + id + "/update?BackURL=" + $.table.encodeTableURL($table);
            });
        }

    },
    getFirstSelectedCheckbox :function($table) {
        var checkbox = $("#table").find(":checkbox:checked:first");
        if(!checkbox.length) {

            //表示不选中 不可以用，此时没必要弹窗
            if(!$(this).hasClass(".no-disable")) {
                return checkbox;
            }

            $.app.alert('请先选择要操作的数据！');
        }
        return checkbox;
    },
    getAllSelectedCheckbox :function($table) {
        var checkbox = $table.find(":checkbox:checked");
        if(!checkbox.length) {

            //表示不选中 不可以用，此时没必要弹窗
            if(!$(this).hasClass(".no-disable")) {
                return checkbox;
            }

            $.app.alert('请先选择要操作的数据！');
        }
        return checkbox;
    }
};

$.array = {
    remove : function(array, data) {
        if(array.length === 0) {
            return;
        }
        for(var i = array.length - 1; i >= 0; i--) {
            if(array[i] === data) {
                array.splice(i, 1);
            }
        }
    },
    contains : function(array, data) {
        if(array.length === 0) {
            return false;
        }
        for(var i = array.length - 1; i >= 0; i--) {
            if(array[i] === data) {
                return true;
            }
        }
        return false;
    },
    indexOf : function(array, data) {
        if(array.length === 0) {
            return -1;
        }
        for(var i = array.length - 1; i >= 0; i--) {
            if(array[i] === data) {
                return i;
            }
        }
        return -1;
    },
    clear : function(array) {
        if(array.length === 0) {
            return;
        }
        array.splice(0, array.length);
    },
    trim : function(array) {
        for(var i = array.length - 1; i >= 0; i--) {
            if(array[i] === "" || array[i] == null) {
                array.splice(i, 1);
            }
        }
        return array;
    }
};

$.object = {
    trim: function(obj, blank) {
        var result = {}, value;
        if ($.isPlainObject(obj)) {
            for(var p in obj) {
                if (obj.hasOwnProperty(p) && (value = obj[p]) !== null && value !== undefined) {
                    if (blank && value === '') {
                        continue;
                    }
                    result[p] = value;
                }
            }
        }
        return result;
    }
};

$.utils = {
    guid: 1,
    guidPref: '_',
    randGuid: function(prefix) {
        return (prefix||$.utils.guidPref) + $.utils.guid++
    },
    getUrlParam: function(url, name) {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = url.split('?')[1].match(reg);
        if(r!=null)return  decodeURIComponent(r[2]); return null;
    },
    getParam: function(name) {
        return this.getUrlParam(location.href, name);
    }
};

$.constant = {
    getSex: function(code) {
        var sex = {male: '男', female: '女'};
        return sex[code] || '未知'
    },
    getBool: function(code) {
        return code ? '是' : '否'
    }
};

(function ($) {
    $.layout = top.$.layout;
    // $.app = top.$.app;
    $.tabs = top.$.tabs;
    $.menus = top.$.menus;

    /**
     * 统一请求设置
     */
    $.ajaxSetup({
        beforeSend:function(jqXHR) {
            // 添加头部，做登录会话提示，如果会话失效，这个惨可以让让返回json，用于提示，而不是请求重定向到登录页面
            jqXHR.setRequestHeader("isApp","YES");
        },
        error: function (event, request) {
            console.log(request)
            $.app.closeLoading();
            if(request.status === 0) {// 中断的不处理
                return;
            }
            top.$.app.alert((request.responseText||'未知异常，请联系管理员！').replace(/(<refresh>.*<\/refresh>)/g, ''), {title : '网络故障/系统故障'});
        },
        cache: true
    });

    var $ajax = $.ajax;
    /**
     * ajax 添加开启 loading 选项
     * $.ajax({url: url, ..., loading: true}) loading为true开启loading
     * $.get(url, function, true) 最后一个参数为true开启loading
     * $.post(url, function, true) 最后一个参数为true开启loading
     */
    $.ajax = function(url, options) {
        if ($.isPlainObject(url)) {
            options = url;
        }

        if (options.loading === true) {
            var beforeSend = options.beforeSend, complete = options.complete;
            options.beforeSend = function() {
                $.isFunction(beforeSend) && beforeSend.apply(this, arguments);
                $.app.openLoading();
            };
            options.complete = function() {
                $.app.closeLoading();
                $.isFunction(complete) && complete.apply(this, arguments);
            };
        }

        return $ajax(url, options);
    };

    $.each( [ "get", "post" ], function( i, method ) {
        $[ method ] = function( url, data, callback, type, loading) {

            // 获取loading选项
            var args = [].slice.call(arguments, 0), len = args.length, loadArg = args[len-1];
            if (loadArg === true || loadArg === false) {
                loading = loadArg;
            }

            if ( $.isFunction( data ) ) {
                type = type || callback;
                callback = data;
                data = undefined;
            }

            // 存在loading选项时，会影响type的值
            if (typeof(type) !== 'string' ) {
                type = undefined;
            }

            return $.ajax({
                url: url,
                type: method,
                dataType: type,
                data: data,
                loading: loading,
                success: callback
            });
        };
    });

    if ($.jgrid) {
        // jqGrid的配置信息
        $.jgrid.defaults.width = 1000;
        $.jgrid.defaults.responsive = true;
        $.jgrid.defaults.styleUI = 'Bootstrap';

        /**
         * 修复jqGrid中getRowData方法获取数据少一行的bug
         */
        $.jgrid.extend({
            getRowData2 : function( rowid, usedata ) {
                var res = {}, resall, getall=false, len, j=0;
                this.each(function(){
                    var $t = this,nm,ind;
                    if(rowid == null) {
                        getall = true;
                        resall = [];
                        len = $t.rows.length-1;
                    } else {
                        ind = $($t).jqGrid('getGridRowById', rowid);
                        if(!ind) { return res; }
                        len = 1;
                    }
                    if( !(usedata && usedata === true && $t.p.data.length > 0)  ) {
                        usedata = false;
                    }
                    while(j<len){
                        if(getall) {
                            ind = $t.rows[j+1];  // ignore first not visible row
                        }
                        if( $(ind).hasClass('jqgrow') ) {
                            if(usedata) {
                                res = $t.p.data[$t.p._index[ind.id]];
                            } else {
                                $('td[role="gridcell"]',ind).each( function(i) {
                                    nm = $t.p.colModel[i].name;
                                    if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn') {
                                        if($t.p.treeGrid===true && nm === $t.p.ExpandColumn) {
                                            res[nm] = $.jgrid.htmlDecode($("span:first",this).html());
                                        } else {
                                            try {
                                                res[nm] = $.unformat.call($t,this,{rowId:ind.id, colModel:$t.p.colModel[i]},i);
                                            } catch (e){
                                                res[nm] = $.jgrid.htmlDecode($(this).html());
                                            }
                                        }
                                    }
                                });
                            }
                            if(getall) { resall.push(res); res={}; }
                        }
                        j++;
                    }
                });
                return resall || res;
            }
        });

        /**
         * 空表格
         */
        function dataIsNull(table) {
            var $table = $(table);
            if($table.getDataIDs().length === 0){
                $table.addClass('no-border').prev().addClass('empty').text('暂无数据').show();
            }else{
                $table.removeClass('no-border').prev().removeClass('empty').hide();
            }
        }

        /**
         * 美化复选框
         */
        function styleCheckbox(table, header) {
            var $grid = $(table);
            // 表格头部复选框
            if (header) {
                $grid = $(table).closest('.ui-jqgrid-view').find('.ui-jqgrid-htable');
            }
            $grid.find('input:checkbox').addClass('ace').wrap('<label class="s_box" />').after('<span class="lbl align-top" />');
        }

        /**
         * 调整frame尺寸
         */
        function adaptiveFrame(table) {
            var $win = $('body')
                , $table = $(table)
                , $parent = $table.parent()
                , $grid = $table.closest('.ui-jqgrid ')
                , $pager = $grid.find('.ui-jqgrid-pager');

            $win.off('resize.jqGrid').on('resize.jqGrid', function () {
                // 调整宽度
                if (table.p.autowidth !== false) {
                    $table.jqGrid('setGridWidth', $parent.width() + 5);
                    $table.width($parent.width() );
                    $grid.find('.ui-jqgrid-htable').width($parent.width());
                }

                // 调整高度
                if (table.p.autoHeight !== false) {
                    $table.jqGrid('setGridHeight', $win.height() - $parent.offset().top - $pager.height() - 32);
                }
            }).trigger('resize.jqGrid');
        }

        $.fn.createGrid = function(options) {

            var defaults, settings;

            // 默认选项
            defaults = {
                datatype: 'json',
                viewrecords: true,
                rowNum: 10,
                rowList : [10,30,50],
                autowidth:true,
                multiselect: true,
                multiboxonly: true,
                showEmpty:true,
                rownumbers:true,
                rownumWidth: 45,
                pager: "#jqGridPager",
                jsonReader : {
                    root: "data.list",
                    page: "data.pageNum",
                    total: "data.pages",
                    records: "data.total"
                },
                prmNames : {
                    page:"page.num",
                    rows:"page.size",
                    order: "order"
                }
            };

            // 禁用排序
            if (options['sortable'] === false) {
                if (options['colModel']) {
                    $.each(options['colModel'], function(i, model){
                        if (model['sortable'] === undefined) {
                            model['sortable'] = false;
                        }
                    });
                }
            }

            // 禁用resize
            if (options['resizable'] === false) {
                if (options['colModel']) {
                    $.each(options['colModel'], function(i, model){
                        if (model['resizable'] === undefined) {
                            model['resizable'] = false;
                        }
                    });
                }
            }

            // 合并默认选项、自定义选项；函数先执行默认的，在执行自定义的
            settings = $.extend(true, defaults, options, {
                beforeProcessing  :function(data){
                    if(!data.success){
                        $.app.alert(data.message);
                    }
                },
                onInitGrid: function() {
                    // 调整尺寸
                    this.adaptiveFrame = adaptiveFrame;
                    this.adaptiveFrame(this);

                    // 复选框样式
                    styleCheckbox(this, true);

                    // 执行自定义函数
                    var onInitGrid = options.onInitGrid;
                    if ($.isFunction(onInitGrid)) {
                        onInitGrid.apply(this, [].splice.call(arguments, 0));
                    }
                },
                loadComplete: function () {
                    var loadComplete = options.loadComplete;

                    // 执行默认操作
                    if (this.p.showEmpty) {
                        dataIsNull(this)
                    }

                    // 复选框样式
                    styleCheckbox(this, false);

                    // 美化滚动条
                    $(this.grid.bDiv).niceScroll({styler:'fb',cursorcolor:'#777', zindex:1});

                    // 执行自定义函数
                    if ($.isFunction(loadComplete)) {
                        loadComplete.apply(this, [].splice.call(arguments, 0));
                    }
                },
                gridComplete:function(){
                    var gridComplete = options.gridComplete;

                    // 执行默认操作
                    if (this.p.showEmpty) {
                        dataIsNull(this)
                    }

                    // 执行自定义函数
                    if ($.isFunction(gridComplete)) {
                        gridComplete.apply(this, [].splice.call(arguments, 0));
                    }
                }
            });

            $(this).jqGrid(settings);

            // 给序号列增加标题名称
            if (settings.rownumbers) {
                $(this).jqGrid('setLabel','rn', '序号', {'text-align':'left'},'');
            }
        }
    }

    /**
     * 获取表单对象
     */
    $.fn.serializeForm = function(){
        var arr = $(this).serializeArray(), form = {};
        $.each(arr, function(i, obj){
            form[obj.name] = obj.value;
        });
        return form;
    };

    /**
     * 日期选择控件
     */
    $.fn.layDate = function(options) {
        return this.each(function(i, input){
            var $input = $(input), elem = 'layDate' + (i+1);
            $input.addClass(elem);
            laydate.render($.extend(true, {
                elem: '.' + elem,
                type: $input.data('dateType') || 'date',
                format: $input.data('dateFormat') || 'yyyy-MM-dd'
            }, options));
        });
    };

    $.fn.heightenTo = function(target, scroll) {
        return this.each(function(i, el){
            var $el = $(el), $target = $(target);
            if (!target || $target.length === 0) {
                $target = $el.parent();
            }
            $(el).height($target.height() - $el.offset().top);
            if (scroll) {
                $(el).css('overflow', 'auto');
            }
        });
    }
})(jQuery);

$(function(){

    // tooltip
    $('[data-tooltip]').each(function() {
        $(this).tooltip({delay:300});
    });

    // 美化滚动条
    $('[data-scroll]').niceScroll({styler:'fb',cursorcolor:'#777', zindex:1});

    // 初始化日期选择
    $('.data').layDate();



    var T = {};

    T.Tab = {
        $tabList: $('#tabList'),
        $tabPanel: $('#tabPanel'),
        active: function(id) {
            $('#tabList,#tabPanel').find('.active').removeClass('active');
            $('[data-tab='+id+']').addClass('active');
            $('iframe[data-tab='+id+']').get(0).contentWindow.location.reload(true);
        },
        add: function(id, title, href) {
            var $title, $panel;

            // 已存在tab
            if ($('[data-tab='+id+']').length) {
                return this.active(id);
            }

            // 构建tab所需节点
            $title = $('<li data-tab="'+id+'" role="presentation"><a href="#'+id+'" role="tab" data-toggle="tab">'+title+'<i class="ace-icon fa fa-times"></i></a></li>');
            $panel = $('<iframe id="'+id+'" class="pos-rel hide" data-tab="'+id+'" src="'+href+'" frameborder="0"></iframe>');

            // 添加tab节点
            this.$tabList.append($title).find('li.active').removeClass('active');
            this.$tabPanel.append($panel).find('iframe.active').removeClass('active');

            // 激活tab
            $title.addClass('active');
            $panel.addClass('active');
        },
        remove: function(id) {
            var prevTab = $('li[data-tab='+id+']').prev().find('a');
            $('[data-tab='+id+']').remove();
            prevTab.click();
            return prevTab.parent().attr('data-tab');
        }
    };

    T.Menu = {
        $parent: $('#menuList'),
        open: function(target) {
            var $menu = $(target), id = $menu.attr('data-menu');
            T.Tab.add(id, $menu.text().trim(), $menu.attr('href'));
            this.active(id);
        },
        active: function(id) {
            var $menu = this.$parent.find('[data-menu='+id+']').parent();
            this.$parent.find('li.open,li.active').removeClass('open active').find('> .submenu').hide();
            $menu.addClass('active').parents('li').addClass('open').find('> .submenu').show();
        }
    };

    T.getUrl = function(url) {
        return (ctx || '/') + url;
    };

    window.T = T;

});
